package com.vrv.es;

/**
 * @author Administrator
 * @ClassName: ElasticsearchAgent
 * @Desc: TODO
 * @Date: 2025/09/29 18:51
 * @Version: 1.0
 * @Modified By:
 */
// ElasticsearchAgent.java

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

import java.lang.instrument.Instrumentation;

public class ElasticsearchAgent {
    public static void premain(String agentArgs, Instrumentation inst) {
        AgentBuilder.Transformer transformer = new AgentBuilder.Transformer() {
            public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule) {
                return builder
                        // 拦截search方法
                        .method(ElementMatchers.named("search"))
                        // 拦截到的方法委托给ElasticsearchSearchInterceptor
                        .intercept(MethodDelegation.to(ElasticsearchSearchInterceptor.class));
            }
        };

        // 配置AgentBuilder以确保使用被代理应用的类加载器和依赖
        new AgentBuilder
                .Default()
                // 指定只拦截RestHighLevelClient类
                .type(ElementMatchers.named("org.elasticsearch.client.RestHighLevelClient"))
                // 设置转换处理器
                .transform(transformer)
                // 安装到Instrumentation
                .installOn(inst);
    }
}
